import { Global, Injectable } from "@nestjs/common";
import { InjectRepository } from "@nestjs/typeorm";
import { Account } from "./account.entities";
import { Repository } from "typeorm";

@Injectable()
export class AccountService {
  @InjectRepository(Account)
  private accountRepository: Repository<Account>;
  constructor() {}

  async createTask(account: Account): Promise<Account> {
    return await this.accountRepository.save(account);
  }

  /**
   * 获取一个随机的账号
   */
  async getAccount(): Promise<Account> {
    const count = await this.accountRepository.count();
    const randomIndex = Math.floor(Math.random() * count);

    return await this.accountRepository
      .createQueryBuilder()
      .select()
      .orderBy("RAND()") // 使用 MySQL 的 RAND() 函数来随机排序
      .offset(randomIndex)
      .limit(1)
      .getOne();
  }
  /**
   * 获取账号列表
   */
  async getAccountList(): Promise<{ accounts: Account[]; total: number }> {
    const [accounts, total] = await this.accountRepository.findAndCount({
      take: 100,
      skip: 0,
      order: { id: "DESC" },
    });

    return {
      accounts,
      total,
    };
  }

  /**
   * 创建账号
   * @param account
   * @returns
   */
  async createAccount(account: Account): Promise<Account> {
    try {
      //查询重复数据
      const hasAccount = await this.getAccountByChannelId(account.channel_id);
      if (hasAccount) {
        throw new Error(`channel_id: ${account.channel_id},账号已存在`);
      }
      const saveAccount = await this.accountRepository.save(account);
      return saveAccount;
    } catch (err) {
      return Promise.reject(err);
    }
  }

  /**
   * 通过channel_id查询是否有已存在
   * @param channel_id
   * @returns
   */
  async getAccountByChannelId(channel_id: string): Promise<Account> {
    const FindOptionsWhere = { channel_id: channel_id };
    const promise = await this.accountRepository.find({
      where: FindOptionsWhere,
      order: { id: "DESC" },
    });
    if (promise.length > 0) {
      return promise[0];
    } else {
      return null;
    }
  }

  /**
   * 更新账号信息
   */
  async updateAccount(account: Account) {
    //通过id查找
    const FindOptionsWhere = { id: account.id };
    return await this.accountRepository.update(FindOptionsWhere, account);
  }
  /**
   * 删除
   */
  async deleteAccount(id: number) {
    //通过id查找
    const FindOptionsWhere = { id: id };
    const promise = await this.accountRepository.find({
      where: FindOptionsWhere,
      order: { id: "DESC" },
    });
    if (promise.length > 0) {
      return await this.accountRepository.delete(promise[0]);
    }
  }
}
